// 权限控制
import { getToken } from '@/utils/auth'
import router from './router'
import store from './store'
import { asyncRoutes } from './router/asyncRoute'

const WHITE_LIST = ['/login', '/404']

// 处理一级路由权限数据
function getFirstRoutePerms(permsArr) {
  const newArr = permsArr.map(item => {
    return item.split(':')[0]
  })
  return [...new Set(newArr)]
}

// 处理二级路由权限数据
function getSecondRoutePerms(permsArr) {
  const newArr = permsArr.map(item => {
    const arr = item.split(':')
    return `${arr[0]}:${arr[1]}`
  })
  return [...new Set(newArr)]
}

// 根据权限标识过滤路由表
function getFilterRoutes(firstRoutePerms, secondRoutePerms, asyncRoutes) {
  // 根据一级和二级对动态路由表做过滤 return出去过滤之后的路由表
  // 1. 根据一级路由对动态路由表做过滤
  return asyncRoutes.filter(route => {
    return firstRoutePerms.includes(route.permission)
  }).map(item => {
    // 2. 对二级路由做过滤
    return {
      ...item,
      children: item.children.filter(item => secondRoutePerms.includes(item.permission))
    }
  })
}

router.beforeEach(async(to, from, next) => {
  const token = getToken()
  // 有token
  if (token) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      // next()
      // 获取用户信息
      if (!store.state.user.profile.id) {
      // 获取原始权限列表
        const perms = await store.dispatch('user/getProfile')
        // 检查是否为管理员
        const isAdmin = perms.some(permission => permission === '*:*:*') // 假设'*.*.*:*'表示管理员权限
        console.log('prems', perms)
        let filterRoutes = []
        if (isAdmin) {
          // 如果是管理员，显示所有菜单
          filterRoutes = asyncRoutes
        } else {
          // 2. 数据处理得到一级二级路由菜单标识
          const firstRoutePerms = getFirstRoutePerms(perms)
          const secondRoutePerms = getSecondRoutePerms(perms)
          // const menuPerms = getMenuList(perms)
          // 3. 通过菜单权限过滤一级和二级得到权限菜单列表
          filterRoutes = getFilterRoutes(firstRoutePerms, secondRoutePerms, asyncRoutes)
        }
        console.log(filterRoutes)
        // 4. addRoute动态添加
        // filterRoutes.forEach(route => router.addRoute(route))
        router.addRoutes([...filterRoutes, { path: '*', redirect: '/404', hidden: true }]) // 添加动态路由信息到路由表
        // 5. 存入Vuex渲染左侧菜单
        store.commit('menu/setMenuList', filterRoutes)
        // 转发
        next(to.path)
      } else {
        next()
      }
    }
  } else {
    // 没有token
    if (WHITE_LIST.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})
